package net.dgg.zz.production.abnormal.service;

import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.tmd.foundation.platform.datapermission.entity.DataAuthDTO;
import net.dgg.tmd.foundation.platform.datapermission.service.DataPermissionAssocService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserManager;
import net.dgg.zz.common.base.service.BaseService;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.production.chargeback.dao.ZzProductOrderDao;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.suspend.service.ZzSubOrderService;
import net.dgg.zz.production.vo.AbnormalOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 赵有文
 * @despriction 异常订单查询Service
 * @create 2018/5/19 0019 下午 3:18
 **/
@Service
public class ZzAbnormalOrderService extends BaseService {
    @Autowired
    private ZzSubOrderService zzSubOrderService;
    @Autowired
    private ZzProductOrderDao zzProductOrderDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private UserManager userManager;
    @Autowired
    private CommonMangerExtService zzCommonMangerExtService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private DataPermissionAssocService dataPermissionAssocService;

    public List<Map> query(Map paras) {
        extraFilter(paras);
        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zz_zzsc_abnormal");
        paras.put("dataAuthDTO", dataAuthDTO);
        paras.put("userAlias", "t");
        paras.put("userColumn", "flow_user_id");
        paras.put("deptAlias", "t");
        paras.put("deptColumn", "flow_user_org_id");
        if (null == paras.get("orderColumn")) {
            paras.put("orderDir", "desc");
            paras.put("orderColumn", "updateTime");
        }
        return zzSubOrderService.queryMap(paras);
    }

    public Integer count(Map paras) {
        extraFilter(paras);
        DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds("zz_zzsc_abnormal");
        paras.put("dataAuthDTO", dataAuthDTO);
        paras.put("userAlias", "t");
        paras.put("userColumn", "flow_user_id");
        paras.put("deptAlias", "t");
        paras.put("deptColumn", "flow_user_org_id");
        return zzSubOrderService.count(paras);
    }

    private void extraFilter(Map para) {
        para.put("userLocked", 2);
        para.put("dataAuthority", "zz_zzsc_abnormal");
    }

    @Transactional
    public void turnoverAbnormal(Map paras) {
        String[] arr = new String[]{"ids", "flowUserId", "remark"};
        UserEntity user = sessionManager.getCurrentUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(new Date());
        for (String name : arr) {
            Assert.isTrue(paras.containsKey(name), String.format("缺少必要参数:%s", name));
        }
        String[] ids = paras.get("ids").toString().split(",");
        String flowUserId = paras.get("flowUserId") + "";
        String remark = paras.get("remark") + "";
        UserEntity flowUser = userManager.findUserById(Long.valueOf(flowUserId));
        Map flowOrg = zzCommonMangerExtService.findOrg(flowUser.getOrgId());
        Assert.notNull(flowOrg, "获取流程人员部门失败！");

        for (String id : ids) {
            //更新订单属性
            ProductOrder order = zzProductOrderDao.getById(Long.valueOf(id));
            order.setFlowUserId(flowUser.getId());
            order.setFlowUserName(flowUser.getRealName() + flowUser.getLoginName());
            order.setFlowUserOrgId(flowUser.getOrgId());
            order.setFlowUserOrgName(flowOrg.get("name") + "");
            order.setRemark(remark);

            if (ScProductConstant.SC_TO_RECEIVE_FPDJS.equals(order.getStatus()) || ScProductConstant.SC_TO_RECEIVE_ZDDJS.equals(order.getStatus())
                    || ScProductConstant.SC_TO_RECEIVE_YJDJS.equals(order.getStatus()) || ScProductConstant.SC_TO_RECEIVE_TDDJS.equals(order.getStatus())){
                if (ScProductConstant.ALLOT_TO_PRODUCT_USER.equals(order.getAllotWay())){//分配给负责人
                    order.setProductUserId(flowUser.getId());//负责人
                    order.setProductUserName(flowUser.getRealName()+flowUser.getLoginName());
                    order.setProductUserOrgId(flowUser.getOrgId());
                    order.setProductUserOrgName(flowOrg.get("name") + "");
                    order.setReceiverId(flowUser.getId());//接收人
                    order.setReceiverName(flowUser.getRealName()+flowUser.getLoginName());
                    order.setReceiverOrgId(flowUser.getOrgId());
                    order.setReceiverOrgName(flowOrg.get("name") + "");
                }else {//接收人
                    order.setReceiverId(flowUser.getId());
                    order.setReceiverName(flowUser.getRealName()+flowUser.getLoginName());
                    order.setReceiverOrgId(flowUser.getOrgId());
                    order.setReceiverOrgName(flowOrg.get("name") + "");
                }
            }

            this.updateOpt(order, sessionManager.getCurrentUser());
            zzProductOrderDao.update(order);
            //增加流程操作记录
            SystemRecord systemRecord = new SystemRecord();
            systemRecord.setRemarks(remark);
            systemRecord.setWorkId(order.getId());
            systemRecord.setWorkNo(order.getScProductOrderNo());
            systemRecord.setWorkTableName("zzsc_product_order");
            systemRecord.setSource("2");//来源生产
            systemRecord.setOperateType("26");//操作类型 : 异常订单移交
            systemRecordService.save(systemRecord,flowUser);
            try {
                //发送推送消息
                String[] msgs = new String[]{order.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                List<UserEntity> users = new ArrayList<>();
                users.add(flowUser);//接收人
                commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_TURN_OVER");//移交模板
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据条件查询记录-导出
     *
     * @param params
     * @return
     */
    public List<AbnormalOrderVo> findByParamsList(Map params) throws Exception {
        List<AbnormalOrderVo> voList = new LinkedList<>();
        List<Map> srList = this.query(params);
        for (int i = 0; i < srList.size(); i++) {
            AbnormalOrderVo vo = new AbnormalOrderVo();
            vo.setSignOrgName(String.valueOf(srList.get(i).get("signOrgName") == null ? "" : srList.get(i).get("signOrgName")));
            vo.setOrderNo(String.valueOf(srList.get(i).get("orderNo") == null ? "" : srList.get(i).get("orderNo")));
            vo.setScProductOrderNo(String.valueOf(srList.get(i).get("scProductOrderNo") == null ? "" : srList.get(i).get("scProductOrderNo")));
            vo.setCustomerName(String.valueOf(srList.get(i).get("customerName") == null ? "" : srList.get(i).get("customerName")));
            vo.setStatus(String.valueOf(srList.get(i).get("status") == null ? "" : srList.get(i).get("status")));
            vo.setLatestEndNodeName(String.valueOf(srList.get(i).get("latestEndNodeName") == null ? "" : srList.get(i).get("latestEndNodeName")));
            vo.setBusinessProductName(String.valueOf(srList.get(i).get("businessProductName") == null ? "" : srList.get(i).get("businessProductName")));
            vo.setProductName(String.valueOf(srList.get(i).get("productName") == null ? "" : srList.get(i).get("productName")));
            vo.setSignTime(String.valueOf(srList.get(i).get("signTime") == null ? "" : srList.get(i).get("signTime")));
            vo.setSignUserName(String.valueOf(srList.get(i).get("signUserName") == null ? "" : srList.get(i).get("signUserName")));
            vo.setSignUserOrgName(String.valueOf(srList.get(i).get("signUserOrgName") == null ? "" : srList.get(i).get("signUserOrgName")));
            vo.setFlowUserName(String.valueOf(srList.get(i).get("flowUserName") == null ? "" : srList.get(i).get("flowUserName")));
            vo.setFlowUserOrgName(String.valueOf(srList.get(i).get("flowUserOrgName") == null ? "" : srList.get(i).get("flowUserOrgName")));
            vo.setCompanyName(String.valueOf(srList.get(i).get("companyName") == null ? "" : srList.get(i).get("companyName")));
            //最新备注时间
            vo.setLastRemarkTime(String.valueOf(srList.get(i).get("lastRemarkTime") == null ? "" : srList.get(i).get("lastRemarkTime")));
            vo.setLastRemark(String.valueOf(srList.get(i).get("lastRemark") == null ? "" : srList.get(i).get("lastRemark")));
            voList.add(vo);
        }
        return voList;
    }
}
